package com.icss.flow.help;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;

/**
 * @author hyk
 */
@RestController
@RequestMapping("/api-info")
public class ApiHelp {

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    @RequestMapping("/list")
    public Map<String, List<String>> listAllApiEndpoints() {
        Map<String, List<String>> apiEndpoints = new HashMap<>();

        Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
            RequestMappingInfo mappingInfo = entry.getKey();
            HandlerMethod handlerMethod = entry.getValue();
            String name = handlerMethod.getBeanType().getName();
            if (Objects.isNull(apiEndpoints.get(name))) {
                apiEndpoints.put(name, new ArrayList<>());
            }
            if (mappingInfo.getPathPatternsCondition() != null) {
                apiEndpoints.get(name).add(mappingInfo.getPathPatternsCondition().toString());
            }

        }

        return apiEndpoints;
    }
}
